package com.cn.wkditui;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.androidquery.AQuery;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2016/4/19.
 */
public class Auth1Activity extends BaseActivity {


    private OSS oss;

    // 运行sample前需要配置以下字段为有效的值
    private static final String endpoint = "http://oss-cn-beijing.aliyuncs.com";
    private static final String accessKeyId = "y3xK2NWMPN6qquOE";
    private static final String accessKeySecret = "7x3I89dZQhC46DQCSwHqmPkuHhzpxr";
//    private static final String uploadFilePath = "ItemPic/";

    private static final String testBucket = "wkww";
    private static final String uploadObject = "ItemPic/";
    private static final String downloadObject = "ItemPic/";
    private String uploadFilePath = "";

    private Uri imageUri;
    private Uri imageCropUri;


    public static int PHOTO_REQUEST_GALLERY = 1;
    public static int PHOTO_REQUEST_CAMERA = 2;
    public static int PHOTO_REQUEST_CUT = 3;
    public static int CAMERA_WITH_DATA = 4;
    public static int PHOTO_PICKED_WITH_DATA = 5;
    private static final int FILE = 6;


    @BindView(R.id.etmdname)
    EditText etmdname;
    @BindView(R.id.ll1)
    LinearLayout ll1;
    @BindView(R.id.etlocation)
    TextView etlocation;
    @BindView(R.id.tvUpload)
    TextView tvUpload;
    @BindView(R.id.ll2)
    LinearLayout ll2;
    @BindView(R.id.etlocationd)
    EditText etlocationd;
    @BindView(R.id.ll3)
    LinearLayout ll3;
    @BindView(R.id.imageView5)
    ImageView imageView5;
    @BindView(R.id.rl)
    RelativeLayout rl;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.bt_cancel)
    Button btCancel;
    @BindView(R.id.iv)
    ProcessImageView iv;
    @BindView(R.id.ll)
    LinearLayout ll;
    @BindView(R.id.tv)
    TextView tv;

    private double lat = 0;
    private double lng = 0;
    private GeoCoder mSearch;
    private boolean isEdit;
    private String id = "";
    private Bitmap bitmap;
    private AQuery aq;
    private String photoName = "";
    private File file;
    private File cropFile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.acitivty_a1);
        ButterKnife.bind(this);
        init();

        if(getIntent().hasExtra("id")){
            id = getIntent().getStringExtra("id");
            load();
        }

        Log.e("Auth1", "是否编辑:" + isEdit);
        if (isEdit) {
            load();
        } else {
//            ...
        }
    }

    private void load() {
        // TODO: 2016/4/20
        RequestParams params = new RequestParams();
        params.addBodyParameter("id", id);
        params.addBodyParameter("type", "1");
        Log.e(",,", "id=====" + id);
        Log.e(",,", "type=====" + 1);
        Log.e(",,", "type=====" + Consts.HOST + Consts.GETSURVER + "/id/" + id + "/type/1");
        new HttpUtils().send(HttpRequest.HttpMethod.POST, Consts.HOST + Consts.GETSURVER, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                try {
                    Log.e(",", "结果" + responseInfo.result);
                    JSONObject json = new JSONObject(responseInfo.result);
                    if (json.getInt("code") == 1) {
                        etmdname.setText(json.getJSONObject("data").getString("name"));
                        province = json.getJSONObject("data").getString("province");
                        city = json.getJSONObject("data").getString("city");
                        lat = Double.parseDouble(json.getJSONObject("data").getString("lat"));
                        lng = Double.parseDouble(json.getJSONObject("data").getString("lng"));
                        etlocation.setText(json.getJSONObject("data").getString("regionNum"));
                        etlocationd.setText(json.getJSONObject("data").getString("address"));
                        if( !json.getJSONObject("data").getString("photo").equals("")){
                            aq.id(iv).image(Consts.IMGPATH+json.getJSONObject("data").getString("photo"));
                            tvUpload.setVisibility(View.GONE);
                            imageView5.setVisibility(View.GONE);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(Auth1Activity.this,"网络异常",Toast.LENGTH_SHORT).show();
            }
        });


    }

    private void init() {

        aq = new AQuery(this);

        if (getIntent().hasExtra("act")) {
            isEdit = true;
            id = getIntent().getStringExtra("id");
        } else {
            isEdit = false;
        }
        createFile();

        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(listener);


//        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
//
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
//        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
//        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
//        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
//        OSSLog.enableLog();
//        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);

    }

    private void createFile() {
        String path = Environment.getExternalStorageDirectory().getPath();


//        file = new File(path + "/temp.jpg");
//        cropFile = new File(path + "/temp_crop.jpg");
//        if (file.exists()) {
//            boolean b = file.delete();
//        }
//        if (cropFile.exists()) {
//            Log.e("this", "删除裁剪图片美女");
//            cropFile.delete();
//        }
//        file = new File(path + "/temp.jpg");
        cropFile = new File(path + "/temp_crop.jpg");
//        imageUri = Uri.fromFile(file);
        imageCropUri = Uri.fromFile(cropFile);
        Log.e("imageUri", "imageUri=============" + imageUri);
        Log.e("imageCropUri", "imageCropUri=============" + imageCropUri);
    }


    private String province = "";
    private String city = "";
    OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有检索到结果
            }

//            Toast.makeText(AuthActivity.this,result.getAddress(),0).show();

            //获取地理编码结果
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            }
            province = result.getAddressDetail().province;
            city = result.getAddressDetail().city;
            Log.e("", "city" + province + city);
            etlocation.setText(result.getAddress());
//            Toast.makeText(AuthActivity.this, result.getAddressDetail().province,0).show();
            //获取反向地理编码结果
        }
    };

    @OnClick({R.id.bt_next, R.id.bt_cancel, R.id.ll2, R.id.rl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_next:
                //TODO
//                new Thread(new Runnable() {
//                    @Override
//                    public void run() {
//                        new PutObjectSamples(oss, testBucket, uploadObject, uploadFilePath).asyncPutObjectFromLocalFile();
//                    }
//                }).start();

                ll1.setBackground(getResources().getDrawable(R.drawable.item_grey));
                ll2.setBackground(getResources().getDrawable(R.drawable.item_grey));
                ll3.setBackground(getResources().getDrawable(R.drawable.item_grey));
                if (TextUtils.isEmpty(etmdname.getText().toString())) {
                    ll1.setBackground(getResources().getDrawable(R.drawable.item_red));
                    etmdname.setHintTextColor(getResources().getColor(R.color.red));
                }
//                else  if(TextUtils.isEmpty(etlocation.getText().toString())){
//                    ll2.setBackground(getResources().getDrawable(R.drawable.item_red));
////                    et.setHintTextColor(getResources().getColor(R.color.red));
//                }
                else if (TextUtils.isEmpty(etlocationd.getText().toString())) {
                    ll3.setBackground(getResources().getDrawable(R.drawable.item_red));
                    etlocationd.setHintTextColor(getResources().getColor(R.color.red));
                } else {

                    String url = Consts.HOST + Consts.ADDSUVER;
//                    new HttpUtils()
                    RequestParams params = new RequestParams();
                    Log.e("Auth1", "id=====" + id);
                    params.addBodyParameter("name", etmdname.getText().toString());
                    params.addBodyParameter("id", id);
                    params.addBodyParameter("lat", lat + "");
                    params.addBodyParameter("lng", lng + "");
                    params.addBodyParameter("lng", lng + "");
                    params.addBodyParameter("province", province);
                    params.addBodyParameter("photo", photoName);
                    params.addBodyParameter("city", city);
                    params.addBodyParameter("address", etlocationd.getText().toString());
                    params.addBodyParameter("regionNum", etlocation.getText().toString());
                    Log.e("auth1", etlocation.getText().toString());
                    params.addBodyParameter("staffPhone", MyPreference.getInstance(Auth1Activity.this).getStaffid());
//                    params.addBodyParameter("staffId",etbh.getText().toString());
//									System.out.println("id"+MyPreference.getInstance(AuthActivity.this).getUser_Id());
                    System.out.println("name" + etmdname.getText().toString());
                    System.out.println("lat" + lat + "");
                    System.out.println("lng" + lng + "");
                    System.out.println("province" + province);
                    System.out.println("city" + city);
//                    System.out.println("address"+name+etstrnum.getText().toString());
//                    System.out.println("staffId"+etbh.getText().toString());

                    HttpUtils httpUtils = new HttpUtils();
                    httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

                        @Override
                        public void onFailure(HttpException arg0, String arg1) {
                            System.out.println("arg1" + arg1);
                            Toast.makeText(getBaseContext(), "网络异常", 0).show();
                        }

                        @Override
                        public void onSuccess(ResponseInfo<String> arg0) {
                            System.out.println("arg0." + arg0.result);
                            try {
                                JSONObject json = new JSONObject(arg0.result);
                                int code = json.getInt("code");
                                if (code == 1) {
                                    Toast.makeText(getBaseContext(), "保存成功", 0).show();
//                                    MyPreference.getInstance(Auth1Activity.this).setToken(json.getJSONObject("data").getString("token"));

                                    Intent intent = new Intent(Auth1Activity.this, QAQActivity.class);
                                    intent.putExtra("id", json.getString("data"));
                                    if (isEdit) {
                                        intent.putExtra("act", "edit");
                                    }
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                } else {
                                    Toast.makeText(getBaseContext(), json.getString("message"), 0).show();
                                }
                            } catch (JSONException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }
                    });
                }

                break;
            case R.id.bt_cancel:
                Auth1Activity.this.finish();
                break;


            case R.id.ll2:

                startActivityForResult(new Intent(Auth1Activity.this, MapActivity.class), 101);
                break;
            case R.id.rl:
                new PopupWindows(Auth1Activity.this, ll, view.getId());
                break;
        }
    }


    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent, final int id) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            final LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LinearLayout.LayoutParams.FILL_PARENT);
            setHeight(LinearLayout.LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            RelativeLayout p = (RelativeLayout) view.findViewById(R.id.parent);
            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);
            p.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    dismiss();
                    ll_popup.clearAnimation();
                }
            });
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
//                    Intent intent = new Intent(ACTION_IMAGE_CAPTURE);
//                    intent.putExtra("id", id);
//                    startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageCropUri);
                    startActivityForResult(intent, CAMERA_WITH_DATA);
                    dismiss();
                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
//					Intent intent = new Intent(PublishedActivity.this,
//							TestPicActivity.class);
//					startActivity(intent);
                    Intent intent2 = new Intent(Intent.ACTION_PICK);
                    intent2.putExtra("id", id);
                    intent2.setType("image/*");
                    startActivityForResult(intent2, PHOTO_REQUEST_GALLERY);
                    dismiss();
                }

            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });

        }
    }

    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }






    private void setImage(Intent data, final ImageView iv) {
        bitmap = data.getParcelableExtra("data");
        tvUpload.setVisibility(View.GONE);
        imageView5.setVisibility(View.GONE);
        aq.id(iv).image(bitmap);

        File filePath = Environment.getExternalStorageDirectory();
        File f = new File(filePath, "test.jpg");


        if (bitmap != null) {
            try {
                FileOutputStream fos = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100,
                        fos);


                initOss();
                OssUpload(f.getAbsolutePath());

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        Log.e("fos", "f" + f.getAbsolutePath());


    }

    private void OssUpload(final String absolutePath) {
        tv.setText("正在上传!");
        // 构造上传请求
        photoName = "ditui_" + System.currentTimeMillis() + ".jpg";
        PutObjectRequest put = new PutObjectRequest(testBucket, uploadObject + photoName, absolutePath);
        Log.e("Auth1", photoName);
        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, final long currentSize, final long totalSize) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        iv.setProgress((int) (((float) currentSize / (float) totalSize) * 100));
                        if (currentSize == totalSize) {
                            tv.setText("图片上传成功!");
                        }
                    }

            });
        }
    });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

    }

    private void initOss() {
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSSLog.enableLog();
        oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
    }


    protected void doCropPhoto(Uri uri) {
        Intent intent = getCropImageIntent(uri);
        startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
    }

    public static Intent getCropImageIntent(Uri uri) {

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
//        startActivityForResult(intent, PHOTO_REQUEST_CUT);

        return  intent;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 201) {
            ll3.setBackground(getResources().getDrawable(R.drawable.item_grey));
            lat = data.getDoubleExtra("lat", 0);
            lng = data.getDoubleExtra("lng", 0);
//            name=data.getStringExtra("name");
//            etlocation.setText(name);
            LatLng latLng = new LatLng(lat, lng);
            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
        }
        ImageView i = null;
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                // 得到图片的全路径
                Uri uri = data.getData();
                crop(uri);
            }
        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            Log.e("Auth1", "datakong me " + (data != null));
            if (data != null) {
                Bitmap bit = data.getParcelableExtra("data");
//                cropImg( bit);
//                setImage(data, iv);
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            if (data != null) {
                setImage(data, iv);
            }
        } else if (requestCode == FILE) {
            Uri uri = data.getData();
            ContentResolver resolver = getContentResolver();

        } else if (requestCode == CAMERA_WITH_DATA) {
            crop(imageCropUri);
//            Log.e("log","Uri"+uri);
//            final Bitmap photo = data.getParcelableExtra("data");
//            if (photo != null) {
//                doCropPhoto(uri);
//            }
        } else if (requestCode == PHOTO_PICKED_WITH_DATA) {
            Bitmap photo1 = data.getParcelableExtra("data");
            if (photo1 != null) {
                setImage(data, iv);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return  true;
    }


}

